package cn.cloudreal.cbms.system.action;

import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import cn.cloudreal.cbms.common.util.Constants;
import cn.cloudreal.cbms.common.util.PageBean;
import cn.cloudreal.cbms.system.service.OrganizaService;
import cn.cloudreal.cbms.system.service.RoleService;
import cn.cloudreal.cbms.system.service.UserInfoService;
import cn.cloudreal.cbms.vo.Purview;
import cn.cloudreal.cbms.vo.UserInfo;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport
{
    /** serialVersionUID */
    private static final long serialVersionUID = 1L;

    /** 日志工具类实例 */
    private static final Logger log = Logger.getLogger(LoginAction.class);

    /** 返回信息 */
    private String message;

    /**
     * 注入UserInfoService 类
     */
    private UserInfoService userInfoService;

    /**
     * 注入OrganizaService 类
     */
    private OrganizaService organizaService;

    /**
     * 注入RoleService 类
     */
    private RoleService roleService;

    /** 用户对象 */
    private UserInfo loginUser;

    /** 分页对象 */
    PageBean page;

    /** 当前页 */
    int currentPage;

    /**
     * 页面头部id
     */
    private String liID;

    /**
     * 导航id
     */
    private String navID;

    /**
     * 登陆
     * 
     * @return
     */
    public String login()
    {

        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter LoginAction login() method,return String");
        }
        // response 对象
        HttpServletResponse response = ServletActionContext.getResponse();
        PrintWriter out = null;
        try
        {
            // 获取PrintWriter对象
            ServletActionContext.getRequest()
                    .setCharacterEncoding(Constants.STR_UTF);
            response.setContentType(Constants.STR_CHARSET);
            out = response.getWriter();

            // 存入session
            HttpSession session = ServletActionContext.getRequest()
                    .getSession();

            UserInfo login = (UserInfo) session.getAttribute(Constants.SESSIONPRKEY);

            // 如果输入值为空 判断 session 是否有值 有 首页 没 登录超时
            if (null == loginUser || null == loginUser.getUserCode())
            {
                // 判断session中是否有数据
                if (null == login || null == login.getUserCode())
                {
                    message = "请输入用户账号密码登录！";
                    return "goLogin";
                }
                else
                {
                    return SUCCESS;
                }
            }
            else
            {
                if (loginUser.getUserCode().equals(""))
                {
                    message = "请输入用户账号和密码！";
                    return "goLogin";
                }
                else
                {

                    // 获取当前输入密码
                    String userID = loginUser.getPassword();
                    // 根据用户名密码查询用户
                    if (null != loginUser.getUserCode())
                    {
                        loginUser.setUserCode(loginUser.getUserCode().trim());
                    }

                    // /实例化临时对象
                    UserInfo tempUser = new UserInfo();
                    tempUser.setUserCode(loginUser.getUserCode());

                    // 执行查询 用户相关信息
                    loginUser = userInfoService.loginUser(tempUser);

                    if (null == loginUser)
                    {
                        loginUser = new UserInfo();
                        message = "用户账号或密码不存在！";
                        return "goLogin";
                    }

                    // 获取用户信息
                    if (null != userID
                            && !userID.equals(loginUser.getPassword()))
                    {
                        loginUser = new UserInfo();
                        message = "用户账号或密码不存在！";
                        return "goLogin";
                    }
                    session.setAttribute(Constants.SESSIONPRKEY, loginUser);

                    // 获取当前用户第一个菜单，第一个跳转url地址
                    List<Purview> purList = loginUser.getPurviewList();

                    Integer parentID = null;

                    if (null != purList)
                    {
                        for (int i = 0; i < purList.size(); i++)
                        {
                            Purview pur = purList.get(i);
                            if (null != pur && pur.getParentId().equals(-1))
                            {
                                parentID = pur.getId();
                                break;
                            }
                        }
                        if (null != parentID)
                        {
                            for (int i = 0; i < purList.size(); i++)
                            {
                                Purview pur = purList.get(i);
                                if (null != pur
                                        && pur.getParentId().equals(parentID))
                                {
                                    // 存储第一个默认url地址
                                    session.setAttribute("firstActionURL",
                                            pur.getActionUrl());
                                    out.print("<script >window.location.href='"
                                            + pur.getActionUrl()
                                            + "';</script>");
                                    return null;
                                    // break;
                                }
                            }
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            log.error("Error LoginAction login() method,return String", e);
            message = "服务器异常！";
            return "goLogin";
        }

        // 打印退出方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Exit LoginAction login() method,return String");
        }
        return null;
        // return SUCCESS;

    }

    /**
     * @description 用户退出
     * @return
     * @throws Exception
     */
    public String logout() throws Exception
    {
        // 进入日志
        if (log.isInfoEnabled())
        {
            log.info("Enter String: logout() method");
        }
        // 清空纪录
        message = new String();
        // 销毁session
        ServletActionContext.getRequest().getSession().invalidate();
        return SUCCESS;
    }

    /**
     * 设置top session参数
     * 
     * @return null
     */
    public String doTopSessionAtrr()
    { // 进入日志
        if (log.isInfoEnabled())
        {
            log.info("Enter String: doSessionAtrr() method");
        }
        try
        {
            // 清空纪录
            HttpSession session = ServletActionContext.getRequest()
                    .getSession();

            // 转码
            liID = URLDecoder.decode(liID, "UTF-8");
            session.setAttribute("liID", liID);
        }
        catch (Exception e)
        {

            log.error("Error LoginAction doTopSessionAtrr() method,return String",
                    e);
        }
        return null;
    }

    /**
     * 设置nav session参数
     * 
     * @return null
     */
    public String doNavSessionAtrr()
    { // 进入日志
        if (log.isInfoEnabled())
        {
            log.info("Enter String: doNavSessionAtrr() method");
        }
        try
        {
            // 清空纪录
            HttpSession session = ServletActionContext.getRequest()
                    .getSession();

            // 转码
            navID = URLDecoder.decode(navID, "UTF-8");
            session.setAttribute("navID", navID);
        }
        catch (Exception e)
        {

            log.error("Error LoginAction doNavSessionAtrr() method,return String",
                    e);
        }
        return null;
    }

    public String getMessage()
    {
        return message;
    }

    public void setMessage(String message)
    {
        this.message = message;
    }

    public UserInfoService getUserInfoService()
    {
        return userInfoService;
    }

    public void setUserInfoService(UserInfoService userInfoService)
    {
        this.userInfoService = userInfoService;
    }

    public OrganizaService getOrganizaService()
    {
        return organizaService;
    }

    public void setOrganizaService(OrganizaService organizaService)
    {
        this.organizaService = organizaService;
    }

    public RoleService getRoleService()
    {
        return roleService;
    }

    public void setRoleService(RoleService roleService)
    {
        this.roleService = roleService;
    }

    public UserInfo getLoginUser()
    {
        return loginUser;
    }

    public void setLoginUser(UserInfo loginUser)
    {
        this.loginUser = loginUser;
    }

    public PageBean getPage()
    {
        return page;
    }

    public void setPage(PageBean page)
    {
        this.page = page;
    }

    public int getCurrentPage()
    {
        return currentPage;
    }

    public void setCurrentPage(int currentPage)
    {
        this.currentPage = currentPage;
    }

    public String getLiID()
    {
        return liID;
    }

    public void setLiID(String liID)
    {
        this.liID = liID;
    }

    public String getNavID()
    {
        return navID;
    }

    public void setNavID(String navID)
    {
        this.navID = navID;
    }

}
